package com.android.tiango.baba.act;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ToggleButton;

import com.android.scsd.tiango.R;
import com.android.tiango.baba.BaBaseActivity;
import com.android.tiango.baba.chosephoto.AlbumGridViewAdapter;
import com.android.tiango.baba.chosephoto.ImageManager2;
import com.android.tiango.baba.util.ImageLoader;
import com.android.tiango.baba.util.PhotosSearch;
import com.android.tiango.baba.util.StringUtils;
import com.android.tiango.baba.util.ToastUtils;
import com.android.tiango.baba.view.AppTitleBar;

public class Actlbum extends BaBaseActivity {
	public static final int MAX_CHOSE = 6;
	public static final int MAX_FILESIZE = 300;
	public static final String MAX_TITLE_PATH = "scsd_tiangouba_upload_";
	private GridView gridView;
	private ArrayList<String> dataList = new ArrayList<String>();
	private HashMap<String, ImageView> hashMap = new HashMap<String, ImageView>();
	private String cameraDir;// = "/DCIM/"
	private ProgressBar progressBar;
	private AlbumGridViewAdapter gridImageAdapter;
	private LinearLayout selectedImageLayout;
	private Button okButton;
	private HorizontalScrollView scrollview;
	private ImageLoader mImageLoader;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_album);
		mImageLoader = new ImageLoader(this, R.drawable.img_loading_default);
		Intent intent = getIntent();
		// Bundle bundle = intent.getExtras();
		// selectedDataList = (ArrayList<String>)
		// bundle.getSerializable("dataList");
		cameraDir = intent.getStringExtra("path");
		// cameraDir = Environment.getExternalStorageDirectory() + "/DCIM/";
		init();
		initListener();

	}

	private void init() {
		mTitleBar = (AppTitleBar) findViewById(R.id.titlebar);
		mTitleBar.setTitle("请选择图片");
		setBackOnClickListener();
		progressBar = (ProgressBar) findViewById(R.id.progressbar);
		progressBar.setVisibility(View.GONE);
		gridView = (GridView) findViewById(R.id.myGrid);
		gridImageAdapter = new AlbumGridViewAdapter(this, dataList, PhotosSearch.selectedDataList);
		gridView.setAdapter(gridImageAdapter);
		refreshData();
		selectedImageLayout = (LinearLayout) findViewById(R.id.selected_image_layout);
		okButton = (Button) findViewById(R.id.ok_button);
		scrollview = (HorizontalScrollView) findViewById(R.id.scrollview);
		initSelectImage();
	}

	private void initSelectImage() {
		if (PhotosSearch.selectedDataList == null)
			return;
		for (final String path : PhotosSearch.selectedDataList) {
			ImageView imageView = (ImageView) LayoutInflater.from(Actlbum.this).inflate(
					R.layout.choose_imageview, selectedImageLayout, false);
			selectedImageLayout.addView(imageView);
			hashMap.put(path, imageView);
			ImageManager2.from(Actlbum.this).displayImage(imageView, path,
					R.drawable.img_loading_default, 100, 100);
			imageView.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					removePath(path);
					gridImageAdapter.notifyDataSetChanged();
				}
			});
		}
		if (PhotosSearch.selectedDataList.size() > 0) {
			mTitleBar.setTitle(getString(R.string.photo_chosed)
					+ PhotosSearch.selectedDataList.size() + getString(R.string.photo_unit));
		} else {
			mTitleBar.setTitle(getString(R.string.photo_toast));
		}
		okButton.setText(getString(R.string.photo_chose_over)
				+ PhotosSearch.selectedDataList.size() + "/" + MAX_CHOSE + ")");
	}

	private void initListener() {

		gridImageAdapter.setOnItemClickListener(new AlbumGridViewAdapter.OnItemClickListener() {

			@SuppressLint("NewApi")
			@Override
			public void onItemClick(final ToggleButton toggleButton, int position,
					final String path, boolean isChecked) {

				if (PhotosSearch.selectedDataList.size() >= MAX_CHOSE) {
					toggleButton.setChecked(false);
					if (!removePath(path)) {
						ToastUtils.showMessage(R.string.photo_chose_over_1 + MAX_CHOSE
								+ R.string.photo_chose_over_2);
					}
					return;
				}
				if (isChecked) {
					// File file = new File(path);
					// FileInputStream fis;
					// try {
					// fis = new FileInputStream(file);
					// int size = fis.available() / 1000;
					// if (size > MAX_FILESIZE) {
					// ToastUtil.showMessage(R.string.toast_file_maxsize);
					// return;
					new CompressPhotoAysTask().execute(path);
					// return;
					// }
					// } catch (Exception e) {
					// return;
					// }
					// if (!hashMap.containsKey(path)) {
					// ImageView imageView = (ImageView) LayoutInflater.from(Actlbum.this)
					// .inflate(R.layout.choose_imageview, selectedImageLayout, false);
					// selectedImageLayout.addView(imageView);
					// imageView.postDelayed(new Runnable() {
					//
					// @Override
					// public void run() {
					//
					// int off = selectedImageLayout.getMeasuredWidth()
					// - scrollview.getWidth();
					// if (off > 0) {
					// scrollview.smoothScrollTo(off, 0);
					// }
					//
					// }
					// }, 100);
					//
					// hashMap.put(path, imageView);
					// PhotosSearch.selectedDataList.add(path);
					// ImageManager2.from(Actlbum.this).displayImage(imageView, path,
					// R.drawable.camera_default, 100, 100);
					// imageView.setOnClickListener(new View.OnClickListener() {
					//
					// @Override
					// public void onClick(View v) {
					// toggleButton.setChecked(false);
					// removePath(path);
					//
					// }
					// });
					// if (PhotosSearch.selectedDataList.size() > 0) {
					// mTitleBar.setTitle(getString(R.string.photo_chosed)
					// + PhotosSearch.selectedDataList.size()
					// + getString(R.string.photo_unit));
					// } else {
					// mTitleBar.setTitle(getString(R.string.photo_toast));
					// }
					// okButton.setText(getString(R.string.photo_chose_over)
					// + PhotosSearch.selectedDataList.size() + "/" + MAX_CHOSE + ")");
					// }
				} else {
					removePath(path);
				}

			}
		});

		okButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// StringBuffer sb = new StringBuffer();
				// int size = PhotosSearch.selectedDataList.size();
				// for (int i = 0; i < size; i++) {
				// if (i != size - 1) {
				// sb.append(PhotosSearch.selectedDataList.get(i));
				// sb.append(",");
				// } else {
				// sb.append(PhotosSearch.selectedDataList.get(i));
				// }
				// }
				// Intent intent = new Intent();
				// intent.putExtra("pics", sb.toString());
				// AlbumActivity.this.startActivity(intent);
				// showActivity(ActPublishTopic.class, true);
				finish();
			}
		});

	}

	private boolean removePath(String path) {
		if (hashMap.containsKey(path)) {
			selectedImageLayout.removeView(hashMap.get(path));
			hashMap.remove(path);
			removeOneData(PhotosSearch.selectedDataList, path);
			if (PhotosSearch.selectedDataList.size() > 0) {
				mTitleBar.setTitle(getString(R.string.photo_chosed)
						+ PhotosSearch.selectedDataList.size() + getString(R.string.photo_unit));
			} else {
				mTitleBar.setTitle(getString(R.string.photo_toast));
			}
			okButton.setText(getString(R.string.photo_chose_over)
					+ PhotosSearch.selectedDataList.size() + "/" + MAX_CHOSE + ")");
			return true;
		} else {
			return false;
		}
	}

	private void removeOneData(ArrayList<String> arrayList, String s) {
		for (int i = 0; i < arrayList.size(); i++) {
			if (arrayList.get(i).equals(s)) {
				arrayList.remove(i);
				return;
			}
		}
	}

	private void refreshData() {

		new AsyncTask<Void, Void, ArrayList<String>>() {

			@Override
			protected void onPreExecute() {
				progressBar.setVisibility(View.VISIBLE);
				super.onPreExecute();
			}

			@Override
			protected ArrayList<String> doInBackground(Void... params) {
				ArrayList<String> tmpList = new ArrayList<String>();
				// ArrayList<String> listDirlocal = listAlldir(new
				// File(cameraDir)); // 文件夹
				// ArrayList<String> listDiranjuke = new ArrayList<String>();
				// listDiranjuke.addAll(listDirlocal);

				// for (int i = 0; i < listDiranjuke.size(); i++) {
				// listAllfile(new File(listDiranjuke.get(i)), tmpList); // 图片文件
				// }
				listAllfile(new File(cameraDir), tmpList);
				return tmpList;
			}

			protected void onPostExecute(ArrayList<String> tmpList) {

				if (Actlbum.this == null || Actlbum.this.isFinishing()) {
					return;
				}
				progressBar.setVisibility(View.GONE);
				dataList.clear();
				dataList.addAll(tmpList);
				gridImageAdapter.notifyDataSetChanged();
				return;
			};

		}.execute();

	}

	private ArrayList<String> listAlldir(File nowDir) {
		ArrayList<String> listDir = new ArrayList<String>();
		nowDir = new File(nowDir.getPath());// Environment.getExternalStorageDirectory()
											// +
		if (!nowDir.isDirectory()) {
			return listDir;
		}

		File[] files = nowDir.listFiles();

		for (int i = 0; i < files.length; i++) {
			if (files[i].getName().substring(0, 1).equals(".")) {
				continue;
			}
			File file = new File(files[i].getPath());
			if (file.isDirectory()) {
				listDir.add(files[i].getPath());
			}
		}
		return listDir;
	}

	private ArrayList<String> listAllfile(File baseFile, ArrayList<String> tmpList) {
		if (baseFile != null && baseFile.exists()) {
			File[] file = baseFile.listFiles();
			for (File f : file) {
				boolean b = (f.getPath().endsWith(".jpg") || f.getPath().endsWith(".png")
						|| f.getPath().endsWith("jpeg") || f.getPath().endsWith(".PNG")
						|| f.getPath().endsWith(".JPG") || f.getPath().endsWith("JPEG"));
				if (b) {
					tmpList.add(f.getPath());
				}
			}
		}
		return tmpList;
	}

	private String getBigPhoto(String path) {
		Bitmap bitmap = mImageLoader.decodeBitmapFromFile(path, 480, 480);
		// 生成本来的文件名
		String newPath = "";
		if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
			newPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator
					+ MAX_TITLE_PATH + System.currentTimeMillis() + ".jpg";
		} else {
			newPath = this.getCacheDir().getAbsolutePath() + File.separator + MAX_TITLE_PATH
					+ System.currentTimeMillis() + ".jpg";
		}
		// 将压缩之后的图片保存到本地
		FileOutputStream fileOutputStream;
		try {
			fileOutputStream = new FileOutputStream(new File(newPath));
			bitmap.compress(Bitmap.CompressFormat.JPEG, 60, fileOutputStream);
		} catch (FileNotFoundException e) {
			newPath = "";
		}
		return newPath;
	}

	class CompressPhotoAysTask extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... arg0) {
			String path = arg0[0];
			if (!StringUtils.isEmpty(path)) {
				return getBigPhoto(path);
			}
			return "";
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (!StringUtils.isEmpty(result)) {
				showChosedPhoto(result);
			}
		}

	}

	private void showChosedPhoto(final String path) {
		if (!hashMap.containsKey(path)) {
			ImageView imageView = (ImageView) LayoutInflater.from(Actlbum.this).inflate(
					R.layout.choose_imageview, selectedImageLayout, false);
			selectedImageLayout.addView(imageView);
			imageView.postDelayed(new Runnable() {

				@Override
				public void run() {

					int off = selectedImageLayout.getMeasuredWidth() - scrollview.getWidth();
					if (off > 0) {
						scrollview.smoothScrollTo(off, 0);
					}

				}
			}, 100);

			hashMap.put(path, imageView);
			PhotosSearch.selectedDataList.add(path);
			ImageManager2.from(Actlbum.this).displayImage(imageView, path,
					R.drawable.camera_default, 100, 100);
			imageView.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// toggleButton.setChecked(false);
					removePath(path);

				}
			});
			if (PhotosSearch.selectedDataList.size() > 0) {
				mTitleBar.setTitle(getString(R.string.photo_chosed)
						+ PhotosSearch.selectedDataList.size() + getString(R.string.photo_unit));
			} else {
				mTitleBar.setTitle(getString(R.string.photo_toast));
			}
			okButton.setText(getString(R.string.photo_chose_over)
					+ PhotosSearch.selectedDataList.size() + "/" + MAX_CHOSE + ")");
		}
	}
}
